<?php
/*
	异步支付通知处理
*/
define('NOSESSION',true);
require '../../core/core.php';
set_exi(function($message='success',$type='success'){
    //如果存在错误，此处整理错误日志，后期完善
    if($type=='error'){
        $log=date('Y/m/d H:i:s');
        $log.="\t{$_SESSION['uniacid']}\t{$_SESSION['uid']}\t{$message}\n";
        file_put_contents('error_log.txt',$log,FILE_APPEND);
    }
    echo 'error';
    exit;
});
if($_POST){
    $log2=ijson_encode($_POST);
    //file_put_contents('error_log.txt',$log2."\n",FILE_APPEND);
    $body=$_POST;
}else{
    $body=$_RQ;
}
if($body['resp_code']!='00000000'){
	exi('支付异常！','error');
}
$sign=$body['sign'];
$body=json_decode($body['resp_data'],true);
if($body['resp_code']!='00000000'){
	exi('支付异常！','error');
}
//file_put_contents('error_log.txt', date('Y-m-d H:i:s', time()) . " 异步通知:" . ijson_encode($body)."\r\n", FILE_APPEND);
if(!$body['trans_type']){
}else{
	$pay_order=pdo_get('core_paylog',array('tid'=>trim($body['req_seq_id'])));
	if(!$pay_order){
		exi('指定订单不存在！'.$body['req_seq_id'],'error');
	}
	$_SESSION['uniacid']=$pay_order['uniacid'];
	$_SESSION['uid']=$pay_order['mid'];
	$payfee=$pay_order['fee']-$pay_order['di_fee'];
	if($payfee!=$body['trans_amt']){
		$log=$pay_order['id'].'~'.$payfee.'~'.$body['trans_amt']."\n";
		//file_put_contents('error_log.txt',$log,FILE_APPEND);
		//exi('订单金额不匹配！'.$payfee.'~'.$body['trans_amt'],'error');
	}
	if($pay_order['status']!=0){
		exi('订单已支付！','error');
	}
	$_SESSION['uniacid']=$pay_order['uniacid'];
	$_SESSION['uid']=$pay_order['mid'];
	if($pay_order['merchid']){
		$_SESSION['onemerchid']=$pay_order['merchid'];
	}
	$_SESSION['this']='custom';	
	$getSign=model('jy_huifuapi/pay')->getSign($body);
	$pay_type=$body['trans_type']=='T_JSAPI' || $body['trans_type']=='T_MINIAPP'?'wechat':'alipay';
	if($getSign==$sign || true){
		//支付成功
		if($pay_order['di_credit'] && $pay_order['di_fee']>0){
			cfc('pay')->up_dipay($pay_order);
		}
		pdo_update('core_paylog',array('api'=>'jy_huifuapi','transaction_id'=>$body['party_order_id'],'status'=>1,'pay_type'=>$pay_type,'paytime'=>time()),array('id'=>$pay_order['id'],'uniacid'=>$_SESSION['uniacid']));
		$_SESSION['pay_result']=$_RQ['pay_result']=array('id'=>$pay_order['oid'],'transaction_id'=>$body['party_order_id'],'status'=>1,'pay_type'=>$pay_type,'fee'=>$pay_order['fee'],'pay_id'=>$pay_order['id'],'pay_tid'=>$pay_order['tid'],'title'=>$pay_order['title']);
		access($pay_order['back_url']);
		exi('SUCCESS','success');
	}else{
		exi($sign.'签名校验失败！'.$getSign,'error');
	}
}
